package com.yusp75.myexam

import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.view.Menu
import android.widget.Toast
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.navigateUp
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.os.LocaleListCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import com.google.android.material.navigation.NavigationView
import com.yusp75.myexam.ad.OpenAdManager.OnShowAdCompleteListener
import com.yusp75.myexam.data.ExcelToRoomHelper
import com.yusp75.myexam.databinding.ActivityMainBinding
import com.yusp75.myexam.ui.home.HomeFragmentDirections
import com.yusp75.myexam.util.FileCopyHelper
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.koin.android.ext.android.getKoin
import java.io.File
import java.io.FileOutputStream


class MainActivity : AppCompatActivity() {

    private lateinit var appBarConfiguration: AppBarConfiguration
    private lateinit var binding: ActivityMainBinding
    private lateinit var helper: ExcelToRoomHelper

    private val DOWNLOAD_PERMISSION_CODE = 1024

    private val adScope = CoroutineScope(Dispatchers.Main + SupervisorJob())

    private suspend fun ensureAdManagerInitialized() {
        (application as MyApp).awaitAdInitialization()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 显示广告，广告关闭后加载主内容
        //lifecycleScope.launch {
        //ensureAdManagerInitialized()
        //showAdSafely()
        //}
        loadMainContent()
        //
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        // Inflate the menu; this adds items to the action bar if it is present.
        return true
    }

    override fun onSupportNavigateUp(): Boolean {
        val navController = findNavController(R.id.nav_host_fragment_content_main)
        return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
    }

    // 初始化db
    fun checkDb() {
        helper = getKoin().get<ExcelToRoomHelper>()
        lifecycleScope.launch(Dispatchers.IO) {
            if (helper.isFirst())
                helper.run {
                    //writeToRoom(binding.root.context, fileName = "低压电工初级培训-629.xlsx")
                    withContext(Dispatchers.Main) {
                        // 检查权限
                        if (!FileCopyHelper.hasDownloadAccess(applicationContext)) {
                            FileCopyHelper.requestDownloadAccess(
                                this@MainActivity,
                                onGranted = {
                                    handlePermissionGranted()
                                })
                        } else {
                            // 拷贝内置文件
                            val fileName = copyAssetToDocuments(
                                applicationContext,
                                "低压电工初级培训-629.xlsx"
                            )?.name ?: "未拷贝"
                            // 跳转到题库管理页
                            //findNavController(R.id.nav_host_fragment_content_main).navigate(R.id.nav_manage_books)
                            val direction =
                                HomeFragmentDirections.actionToBookListFragment(fileName = fileName)
                            findNavController(R.id.nav_host_fragment_content_main).navigate(
                                direction
                            )
                        }
                    }
                    // helper.run
                }
        }

    }

    fun copyAssetToDocuments(context: Context, assetFileName: String): File? {
        return try {
            // 获取目标目录（Documents）
            val documentsDir = File(
                Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOWNLOADS
                ), ""
            )

            // 创建目标文件
            val destFile = File(documentsDir, assetFileName)
            if (destFile.exists()) {
                //print(destFile)
                destFile.delete()
            }

            // 打开assets文件流
            context.assets.open(assetFileName).use { inputStream ->
                // 写入目标文件
                FileOutputStream(destFile).use { outputStream ->
                    inputStream.copyTo(outputStream)
                }
            }
            destFile
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

    private fun showAdSafely() {
        adScope.launch {
            try {
                ensureAdManagerInitialized()
                (application as MyApp).openAdManager.showAdIfAvailable(
                    activity = this@MainActivity,
                    listener = object : OnShowAdCompleteListener {
                        override fun onShowAdComplete() {
                            loadMainContent()
                        }
                    }
                )
            } catch (e: Exception) {
                Log.e("Ads", "广告展示失败: ${e.message}")
                loadMainContent() // 降级处理
            }
        }
    }

    // 主内容加载
    private fun loadMainContent() {
        AppCompatDelegate.setApplicationLocales(
            LocaleListCompat.forLanguageTags("zh-CN")
        )

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        setSupportActionBar(binding.appBarMain.toolbar)
        // 左侧导航栏
        val drawerLayout: DrawerLayout = binding.drawerLayout
        val navView: NavigationView = binding.navView
        val navController = findNavController(R.id.nav_host_fragment_content_main)
        appBarConfiguration = AppBarConfiguration(
            setOf(
                R.id.nav_home, R.id.nav_display, R.id.nav_browse, R.id.nav_help, R.id.nav_setting
            ), drawerLayout
        )
        setupActionBarWithNavController(navController, appBarConfiguration)
        navView.setupWithNavController(navController)

        // db check and  import
        checkDb()
    }

    // 存储权限回调
    // 存储权限回调精简版
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            DOWNLOAD_PERMISSION_CODE -> {
                if (grantResults.isNotEmpty() &&
                    grantResults[0] == PackageManager.PERMISSION_GRANTED
                ) {
                    // 权限授予后的处理
                    handlePermissionGranted()
                } else {
                    // 可选：添加权限拒绝处理逻辑
                    Toast.makeText(this, "无权限,无法拷贝默认题目文件", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }


    private fun handlePermissionGranted() {
        // 统一处理权限获取成功后的操作
        copyAssetToDocuments(this, "低压电工初级培训-629.xlsx")
        findNavController(R.id.nav_host_fragment_content_main).navigate(R.id.nav_manage_books)
    }


    override fun onDestroy() {
        super.onDestroy()
        adScope.cancel()
    }

// end
}